package com.zone.domain.strategy.service.rule.chain.impl;

import com.zone.domain.strategy.model.entity.StrategyRuleEntity;
import com.zone.domain.strategy.model.valobj.RuleActionEnum;
import com.zone.domain.strategy.model.valobj.RuleEnums;
import com.zone.domain.strategy.repository.IStrategyRepository;
import com.zone.domain.strategy.service.rule.chain.AbstractRaffleRuleFilter;
import com.zone.domain.strategy.service.rule.chain.RaffleRuleFilterChain;
import com.zone.types.exception.BizException;
import com.zone.types.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author: zongzi
 * @description: 黑名单过滤器
 * @date: 2024/6/2
 */
@Slf4j
@Service
@Order(1)
public class BlacklistRaffleRuleFilter extends AbstractRaffleRuleFilter {
    @Autowired
    private IStrategyRepository strategyRepository;

    @Override
    protected boolean isSupport(List<String> ruleModels) {
        return ruleModels.contains(RuleEnums.RuleModelEnum.RULE_BLACKLIST.getCode());
    }

    @Override
    protected RaffleRuleFilterChain.StrategyAwardVO execute(Long strategyId, String userId) {
        // 获取黑名单策略规则配置明细(没有配置直接返回)
        List<StrategyRuleEntity> blacklistStrategyRuleList = strategyRepository.queryStrategyRules(strategyId, RuleEnums.RuleModelEnum.RULE_BLACKLIST.getCode());
        if (CollectionUtils.isEmpty(blacklistStrategyRuleList)) {
            throw new BizException("未查询到黑名单配置信息！");
        }
        // 执行黑名单过滤
        for (StrategyRuleEntity strategyRuleEntity : blacklistStrategyRuleList) {
            Map<Integer, List<String>> blacklistTable = strategyRuleEntity.parseBlacklistRuleValues();
            for (Integer awardId : blacklistTable.keySet()) {
                List<String> userIds = blacklistTable.get(awardId);
                if (userIds.contains(userId)) {
                    return RaffleRuleFilterChain.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardConfig("1,10")
                            .ruleAction(RuleActionEnum.INTERCEPT)
                            .build();
                }
            }
        }
        // 不在黑名单中则放行请求
        return RaffleRuleFilterChain.StrategyAwardVO.allow();
    }
}
